package eclipse_sync_plugin;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class PluginControlView extends ViewPart {
    public static final String ID = "eclipse_sync_plugin.PluginControlView";
    private Button toggleButton;
    private boolean isPluginActive = false;
    private Process pythonProcess;
    private Activator activator;
    private Path persistentScriptPath;

    public PluginControlView() {
        activator = Activator.getDefault();
        String userHome = System.getProperty("user.home");
        Path syncPluginDir = Paths.get(userHome, ".eclipse-cursor-sync-plugin");
        this.persistentScriptPath = syncPluginDir.resolve("eclipse_jumper_v2.py");
    }

    @Override
    public void createPartControl(Composite parent) {
        // 设置布局
        parent.setLayout(new GridLayout(1, false));
        
        // 创建按钮
        toggleButton = new Button(parent, SWT.PUSH);
        toggleButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        toggleButton.setText("启动插件");
        
        // 添加按钮点击事件
        toggleButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                togglePlugin();
            }
        });
    }

    private void togglePlugin() {
        if (activator != null) {
            if (!isPluginActive) {
                // 启动插件
                try {
                    activator.startPlugin();
                    startPythonScript();
                    toggleButton.setText("关闭插件");
                    isPluginActive = true;
                } catch (Exception ex) {
                    activator.log(org.eclipse.core.runtime.Status.ERROR, "启动插件失败", ex);
                }
            } else {
                // 关闭插件
                try {
                    activator.stopPlugin();
                    stopPythonScript();
                    toggleButton.setText("启动插件");
                    isPluginActive = false;
                } catch (Exception ex) {
                    activator.log(org.eclipse.core.runtime.Status.ERROR, "关闭插件失败", ex);
                }
            }
        }
    }

    private void extractPythonScriptToPersistentLocation() throws IOException {
        // 确保目录存在
        Path parentDir = persistentScriptPath.getParent();
        if (!Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
            activator.log(org.eclipse.core.runtime.Status.INFO, "创建持久化脚本目录: " + parentDir.toString(), null);
        }

        // 从jar包中读取Python脚本并复制到持久化位置
        try (InputStream is = getClass().getResourceAsStream("/eclipse_jumper_v2.py")) {
            if (is == null) {
                throw new IOException("无法在jar包中找到Python脚本: /eclipse_jumper_v2.py");
            }
            // 复制到持久化文件
            Files.copy(is, persistentScriptPath, StandardCopyOption.REPLACE_EXISTING);
            activator.log(org.eclipse.core.runtime.Status.INFO, "Python脚本已成功提取到持久化位置: " + persistentScriptPath.toString(), null);
        } catch (IOException e) {
            activator.log(org.eclipse.core.runtime.Status.ERROR, "提取Python脚本到持久化位置失败", e);
            throw e; // 重新抛出异常，让上层捕获
        }
    }

    private void startPythonScript() {
        try {
            // 提取Python脚本到持久化位置
            extractPythonScriptToPersistentLocation();
            
            // 获取配置的路径
            String eclipsePath = activator.getPreferenceStore().getString(PluginPreferencePage.PREF_ECLIPSE_PATH);
            String cursorPath = activator.getPreferenceStore().getString(PluginPreferencePage.PREF_CURSOR_PATH);
            String pythonPath = activator.getPreferenceStore().getString(PluginPreferencePage.PREF_PYTHON_PATH);

            // 检查Python解释器路径是否有效
            if (pythonPath == null || pythonPath.trim().isEmpty()) {
                activator.log(org.eclipse.core.runtime.Status.ERROR, "Python解释器路径未配置。请在Eclipse偏好设置中 'Eclipse-Cursor同步' 页面设置Python解释器可执行文件的完整路径 (例如: C:\\Python39\\python.exe)。", null);
                return; // 停止执行
            }
            
            // 构建命令
            ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, persistentScriptPath.toAbsolutePath().toString());
            
            // 传递环境变量
            Map<String, String> env = processBuilder.environment();
            env.put("ECLIPSE_PATH", eclipsePath);
            env.put("CURSOR_PATH", cursorPath);
            
            // 调试日志：打印完整的执行命令和环境变量
            activator.log(org.eclipse.core.runtime.Status.INFO, "Python解释器路径: " + pythonPath, null);
            activator.log(org.eclipse.core.runtime.Status.INFO, "Python执行命令: " + Arrays.toString(processBuilder.command().toArray()), null);
            activator.log(org.eclipse.core.runtime.Status.INFO, "ECLIPSE_PATH环境变量: " + eclipsePath, null);
            activator.log(org.eclipse.core.runtime.Status.INFO, "CURSOR_PATH环境变量: " + cursorPath, null);
            
            // 将子进程的错误流和输出流重定向到父进程的流
            processBuilder.inheritIO();

            // 启动进程
            pythonProcess = processBuilder.start();
            activator.log(org.eclipse.core.runtime.Status.INFO, "Python脚本进程已启动。", null);
            
        } catch (IOException e) {
            activator.log(org.eclipse.core.runtime.Status.ERROR, "启动Python脚本失败", e);
        } catch (Exception e) {
            activator.log(org.eclipse.core.runtime.Status.ERROR, "启动Python脚本时发生未知错误", e);
        }
    }

    private void stopPythonScript() {
        if (pythonProcess != null) {
            activator.log(org.eclipse.core.runtime.Status.INFO, "正在停止Python脚本进程...", null);
            pythonProcess.destroy();
            try {
                if (!pythonProcess.waitFor(5, TimeUnit.SECONDS)) { // 等待最多5秒
                    pythonProcess.destroyForcibly(); // 强制终止
                    activator.log(org.eclipse.core.runtime.Status.WARNING, "Python脚本进程未能正常停止，已强制终止。", null);
                }
                int exitCode = pythonProcess.exitValue();
                activator.log(org.eclipse.core.runtime.Status.INFO, "Python脚本进程已停止，退出码: " + exitCode, null);
            } catch (InterruptedException e) {
                activator.log(org.eclipse.core.runtime.Status.ERROR, "停止Python脚本时中断", e);
                Thread.currentThread().interrupt(); // 恢复中断状态
            } catch (Exception e) {
                activator.log(org.eclipse.core.runtime.Status.ERROR, "停止Python脚本失败", e);
            }
            pythonProcess = null;
        }
    }

    @Override
    public void setFocus() {
        toggleButton.setFocus();
    }

    @Override
    public void dispose() {
        // 在视图销毁时停止Python进程
        stopPythonScript();
        super.dispose();
    }
} 